<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑区域 -->
      <sub-bread />
      <!-- 筛选条件 -->
      <sub-filter></sub-filter>

      <div class="goods-list">
        <!-- 排序区域 -->
        <sub-sort></sub-sort>
        <!-- 商品列表区域 -->
        <SubList></SubList>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, onMounted, provide } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryFilter } from '@/api/category'
import SubBread from './components/SubBread.vue'
import SubFilter from './components/SubFilter.vue'
import SubSort from './components/SubSort.vue'
import SubList from './components/SubList.vue'
export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    SubList
  },
  setup () {
    const subCategoryData = ref({})
    const route = useRoute()

    provide('subCategoryData', subCategoryData)

    // 提供筛选条件的数据
    const filterParams = ref({
      // 自己选择的筛选条件
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    })
    provide('filterParams', filterParams)

    const getSubCategoryData = async () => {
      const { result } = await findSubCategoryFilter(route.params.id)

      // 添加默认筛选条件
      // 因为全部没有，所以需要自己手动添加
      result.brands.forEach((brand) => {
        brand.selected = false
      })
      result.brands.unshift({
        id: null,
        name: '全部',
        selected: true
      })

      result.saleProperties.forEach((item) => {
        item.properties.selected = false

        item.properties.unshift({
          id: null,
          name: '全部',
          selected: true
        })
      })

      subCategoryData.value = result
      // 依赖注入的时候不可以在获取到数据之后，请求延迟
      // provide('subCategoryData', subCategoryData)
    }

    onMounted(() => {
      getSubCategoryData()
    })

    // 解决缓存问题
    // onBeforeRouteUpdate((to) => {
    //   loadSubData(to.params.id)
    // })
  }
}
</script>
